package cn.yoaket.algorithm;

import cn.yoaket.file.DataPhrase;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Polygon;
import cn.yoaket.unit.Edge;

import java.util.ArrayList;
import java.util.List;

public class Shadow {
   public static Polygon projection(Polygon p,double ver, double azi) {

       GeometryFactory factory = new GeometryFactory();
        ver = ver / 180 * Math.PI;
        azi = azi / 180 * Math.PI;

        Coordinate[] points = p.getCoordinates();

        //假设一层楼3m
        double trans = (int)p.getUserData() * 3.0 / Math.tan(ver);
        double lon = trans / Math.tan(azi);

        lon   *= 360.0 / (40030173 * 0.933);
        trans *= 360.0 / (40030173 * 0.933);

        List<Polygon> pros = new ArrayList<>();
        for(int i = 1;i<points.length;++i){
                Coordinate[] pro = new Coordinate[5];
                pro[0] = new Coordinate(points[i]);
                pro[1] = new Coordinate(points[i - 1]);
                pro[2] = new Coordinate(points[i - 1].getX() + lon, points[i - 1].getY() + trans);
                pro[3] = new Coordinate(points[i].getX() + lon, points[i].getY() + trans);
                pro[4] = new Coordinate(points[i]);
                pros.add(factory.createPolygon(pro));
        }
       Geometry union = factory.createPolygon(p.getCoordinates());
       for (Polygon pro : pros) {
           try {
               union = union.union(pro);
           }catch (Exception ignored){}
       }
        return (Polygon)union;
    }
    public static List<Polygon> getRatio(Edge edge, List<Polygon> shadows){
        edge.setRatio(0);
        Polygon road = edge.toPolygon();

        GeometryFactory factory = new GeometryFactory();
        List<Polygon> interShadows = new ArrayList<>();
        for (Polygon shadow : shadows) {
            try {
                if(shadow.intersects(road)){
                    interShadows.add((Polygon) shadow.intersection(road));
                }
            }catch (Exception ignored){}
        }

        if(interShadows.size() > 0) {
            try {
            Geometry union = factory.createPolygon(interShadows.get(0).getCoordinates());
            for (int i = 1; i < interShadows.size(); ++i) {
                    union = union.union(interShadows.get(i));
            }
            edge.setRatio(union.getArea() / road.getArea());
            } catch (Exception ignored) {}
        }
        return interShadows;
    }

}
